<template>
  <div class="team-list">
      <div style="margin-bottom:12px;">
        <el-button type="primary" @click="openAddDialog">新增排班</el-button>
      </div>
      <!-- 排班列表 -->
      <el-table :data="teamList" stripe>
        <el-table-column prop="teamId" label="排班ID" width="100" />
        <el-table-column prop="teamName" label="排班名称" width="150" />
        <el-table-column label="排班类型" width="150">
          <template #default="scope">
            {{ getTeamTypeName(scope.row.teamTypeId) }}
          </template>
        </el-table-column>
        <el-table-column prop="teamLeader" label="排班负责人" width="120" />
        <el-table-column prop="teamStatus" label="排班状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.teamStatus==0">禁用</el-tag>
            <el-tag v-else >启用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" text @click="openEditDialog(scope.row)">编辑</el-button>
            <el-divider direction="vertical" />
            <el-button size="small" type="success" text @click="goToMemberList(scope.row.teamId)">添加成员</el-button>
            <el-divider direction="vertical" />
            <el-button size="small" type="danger" text @click="confirmDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增/编辑 排班对话框 -->
      <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑排班' : '新增排班'" width="520px">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="96px">
          <el-form-item label="排班名称" prop="teamName">
            <el-input v-model="form.teamName" placeholder="请输入排班名称" />
          </el-form-item>
          <el-form-item label="排班类型" prop="teamTypeId">
            <el-select v-model="form.teamTypeId" placeholder="请选择排班类型" style="width:100%">
              <el-option v-for="t in teamtypelist" :key="t.teamTypeId" :label="t.teamTypeName" :value="t.teamTypeId" />
            </el-select>
          </el-form-item>
          <el-form-item label="负责人" prop="teamLeaderId">
            <el-select v-model="form.teamLeaderId" placeholder="请选择负责人" style="width:100%" @change="onLeaderChange">
              <el-option 
                v-for="user in availableUsers" 
                :key="user.id" 
                :label="user.userName" 
                :value="user.id"
                :disabled="user.isUsed"
              >
                <span :class="{ 'disabled-user': user.isUsed }">
                  {{ user.userName }}
                  <el-tag v-if="user.isUsed" size="small" type="warning" effect="plain">已被使用</el-tag>
                </span>
              </el-option>
            </el-select>
            <div v-if="selectedLeaderInfo" class="leader-info">
              <el-tag v-if="selectedLeaderInfo.isUsed" type="warning" effect="plain">
                该负责人已被 {{ selectedLeaderInfo.usedBy }} 使用
              </el-tag>
              <el-tag v-else type="success" effect="plain">
                该负责人可用
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item label="状态" prop="teamStatus">
            <el-select v-model="form.teamStatus" placeholder="请选择状态" style="width:100%">
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" :loading="saving" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getReadClient, getWriteClient, Read } from '@/Urls/AxiosHelper'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
// @ts-ignore
import { useCounterStore } from '@/stores/counter'

const router = useRouter()

const Page=reactive({
  pageindex:1,
  pagesize:10,
  totalcount:0,
  totalpage:0,
})

const teamList = ref<any[]>([])
const teamtypelist = ref<any[]>([])
const userList = ref<any[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)
const formRef = ref()
const form = ref<any>({ teamStatus:1 })

const rules = {
  teamName: [{ required:true, message:'请输入排班名称', trigger:'blur' }],
  teamTypeId: [{ required:true, message:'请选择排班类型', trigger:'change' }],
  teamLeaderId: [
    { required:true, message:'请选择负责人', trigger:'change' },
    { validator: validateLeader, trigger:'change' }
  ],
  teamStatus: [{ required:true, message:'请选择状态', trigger:'change' }],
}

// 验证负责人是否可用
function validateLeader(rule: any, value: any, callback: any) {
  if (!value) {
    callback()
    return
  }
  
  const selectedUser = availableUsers.value.find(u => u.id === value)
  if (selectedUser && selectedUser.isUsed && !isEdit.value) {
    callback(new Error(`该负责人已被 ${selectedUser.usedBy} 使用，不能重复分配`))
  } else {
    callback()
  }
}

// 计算可用的用户列表（标记已使用的负责人）
const availableUsers = computed(() => {
  return userList.value.map(user => {
    // 查找该用户是否已经被其他班组使用
    const usedTeam = teamList.value.find(team => 
      team.teamLeader === user.userName && team.teamId !== form.value.teamId
    )
    
    return {
      ...user,
      isUsed: !!usedTeam,
      usedBy: usedTeam ? usedTeam.teamName : ''
    }
  })
})

// 当前选择的负责人信息
const selectedLeaderInfo = computed(() => {
  if (!form.value.teamLeaderId) return null
  
  const user = availableUsers.value.find(u => u.id === form.value.teamLeaderId)
  return user ? {
    isUsed: user.isUsed,
    usedBy: user.usedBy,
    userName: user.userName
  } : null
})

// 负责人选择变化时的处理
function onLeaderChange(value: any) {
  const user = availableUsers.value.find(u => u.id === value)
  if (user && user.isUsed && !isEdit.value) {
    ElMessage.warning(`该负责人已被 ${user.usedBy} 使用，请选择其他负责人`)
    form.value.teamLeaderId = undefined
  }
}
// 根据 teamTypeId 获取名称（使用 TeamTypeList 的数据）
function getTeamTypeName(id?: number){
  if(id===undefined || id===null) return '-'
  const match = teamtypelist.value.find((t:any)=> t && t.teamTypeId === id)
  return match?.teamTypeName || '-'
}


// 获取排班列表（使用封装的 Read 客户端）
const fetchTeamList = async () => {
  try{
    const teamread = getReadClient(1)
    const res = await teamread.get('schedread/api/Team/GetTeam',{
      params:{ pageindex:Page.pageindex, pagesize:Page.pagesize }
    })
    const data = res?.data?.data
    teamList.value = data?.data || []
    // 按最新MCP字段：totalCount/totalPage（兼容后端大小写差异）
    Page.totalcount = data?.totalCount ?? data?.totalcount ?? 0
    Page.totalpage  = data?.totalPage  ?? data?.totalpage  ?? 0
  }catch(e){
    console.error('GetTeam 调用失败', e)
  }
}
 const teamread = getReadClient(1)
// 获取排班类型（使用 Read）
const TeamTypeList = async ()=>{
  try{
   
    const res = await teamread.get('schedread/api/Team/GetTeamType')
    teamtypelist.value = res?.data?.data || []
  }catch(e){
    console.error('GetTeamType 调用失败', e)
  }
}

// 获取用户列表（使用主API服务器的Read客户端）
const getUserList = async () => {
  try {
    const userread = getReadClient(4) // 使用主API服务器端口
    const res = await userread.get('sysread/api/Organize/GetUser')
    userList.value = res?.data?.data || []
  } catch(e) {
    console.error('GetUser 调用失败', e)
  }
}

onMounted(()=>{
  fetchTeamList()
  TeamTypeList()
  getUserList()
})

function openAddDialog(){
  isEdit.value = false
  form.value = { teamStatus:1 }
  dialogVisible.value = true
}

function openEditDialog(row:any){
  isEdit.value = true
  form.value = { ...row }
  // 根据teamLeader找到对应的用户ID
  if(row.teamLeader) {
    const user = userList.value.find((u:any) => u.userName === row.teamLeader)
    if(user) {
      form.value.teamLeaderId = user.id
    }
  }
  dialogVisible.value = true
}

async function submitForm(){
  try{
    // @ts-ignore
    await formRef.value?.validate()
    
    // 最终检查：确保负责人没有被其他班组使用（新增时）
    if (!isEdit.value) {
      const selectedUser = userList.value.find((u:any) => u.id === form.value.teamLeaderId)
      if (selectedUser) {
        const usedTeam = teamList.value.find(team => team.teamLeader === selectedUser.userName)
        if (usedTeam) {
          ElMessage.error(`该负责人已被 ${usedTeam.teamName} 使用，不能重复分配`)
          return
        }
      }
    }
    
    saving.value = true
    // 根据teamLeaderId获取用户名
    const selectedUser = userList.value.find((u:any) => u.id === form.value.teamLeaderId)
    const teamLeader = selectedUser ? selectedUser.userName : ''
    
    const payload:any = {
      teamId: form.value.teamId,
      teamName: form.value.teamName,
      teamTypeId: form.value.teamTypeId,
      teamLeader: teamLeader,
      teamStatus: form.value.teamStatus,
    }
    const store = useCounterStore()
    const config = { headers: { Authorization: 'Bearer ' + (store?.User?.Token||'') } }
    const teamawait = getWriteClient(1)
    const res = isEdit.value
      ? await teamawait.post('schedwrite/api/Team/UpdTeam', payload, config)
      : await teamawait.post('schedwrite/api/Team/AddTeam', payload, config)
    if(res?.data?.code === 200 || res?.data?.isSuccess){
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      dialogVisible.value = false
      fetchTeamList()
    }else{
      ElMessage.error(res?.data?.message || '提交失败')
    }
  }catch(e){
    ElMessage.error('请求失败')
  }finally{
    saving.value = false
  }
}

async function confirmDelete(row:any){
  await ElMessageBox.confirm(`确认删除排班「${row.teamName}」吗？`, '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
  try{
    const write = getWriteClient(1)
    await write.get('schedwrite/api/Team/DelTeam', { params: { teamId: row.teamId } })
    ElMessage.success('删除成功')
    fetchTeamList()
  }catch(e){
    ElMessage.error('删除失败')
  }
}

// 跳转到团队成员列表页面
function goToMemberList(teamId: number) {
  router.push(`/Main/scheduling/team-member-list/${teamId}`)
}

</script>

<style scoped>
.team-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-table {
  margin-top: 16px;
}
.leader-info {
  margin-top: 8px;
}
.disabled-user {
  color: #999;
}
</style>